<template>
  <div>
    <Spin size="large" fix v-if="spinShow"></Spin>
    <Row>
      <Col span="18">
      <Card>
        <Form ref="formConcert" :label-width="80">
          <FormItem label="演出标题">
            <Input v-model="concert.title"/>
          </FormItem>
          <FormItem label="演出封面">
            <div>
              <div class="poster-upload" v-if="hasPoster">
                <img :src="defaultPoster.imageBase">
                <div class="poster-cover">
                  <Icon type="ios-eye-outline" size="40" @click.native="showPoster()"></Icon>
                  <Icon type="ios-trash-outline" size="40" @click.native="removePoster()"></Icon>
                </div>
              </div>
              <div v-else>
                <Progress v-if="defaultPoster.showProgress" :percent="defaultPoster.percentage" hide-info></Progress>
              </div>
            </div>
            <Upload ref="upload" v-show="!hasPoster"
                    :default-file-list="uploadList" :show-upload-list="false" :on-success="handleSuccess"
                    :format="['jpg','jpeg','png']" :max-size="2048" :on-format-error="handleFormatError"
                    :on-exceeded-size="handleMaxSize" :before-upload="handleBeforeUpload" type="drag"
                    action="http://localhost:8080/api/file/upload" style="display: inline-block;width:200px;">
              <div style="width: 200px;height:200px;line-height: 200px;">
                <Icon type="camera" size="40"></Icon>
              </div>
            </Upload>
            <Modal title="View Image" v-model="posterShow">
              <img :src="defaultPoster.imageBase" v-if="posterShow" style="width: 100%">
            </Modal>
          </FormItem>
          <FormItem label="简单描述">
            <Input v-model="concert.shortDesc"/>
          </FormItem>
          <FormItem label="演出地点">
            <Input v-model="concert.place"/>
          </FormItem>
          <FormItem label="演出时间">
            <Col span="16">
            <Table stripe border :loading="timeEdit" :columns="bHeader" v-bind:data="concert.concertTime"></Table>
            </Col>
            <Col span="4" style="margin-left: 10px;">
            <Button icon="ios-plus-empty" type="success" @click="addTime">添加场次</Button>
            </Col>
            <Modal title="添加时间项" v-model="timeEdit" class-name="vertical-center-modal" @on-ok="timeOk"
                   @on-cancel="timeCencel" :mask-closable="false" :closable="false">
              <Form ref="timeForm" :model="timeData">
                <FormItem label="选择日期">
                  <DatePicker type="date" format="yyyy/MM/dd" placeholder="Select date"
                              v-model="timeData.date"></DatePicker>
                  <Button icon="ios-plus-empty" type="success" size="small" @click="addDateTime">添加时间</Button>
                </FormItem>
                <FormItem label="选择时间" v-for="(tim, index) in timeData.time" :key="index">
                  <TimePicker format="HH:mm" type="time" placeholder="Select time"
                              v-model="timeData.time[index]"></TimePicker>
                </FormItem>
              </Form>
            </Modal>
          </FormItem>
          <FormItem label="座位类型">
            <RadioGroup v-model="concert.seatType">
              <Radio label="0">区域座位</Radio>
              <Radio label="1">常规座位</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="座位票面">
            <Col span="16">
            <Table stripe border :loading="faceEdit" :columns="cHeader" v-bind:data="concert.faceValues"></Table>
            </Col>
            <Col span="4" style="margin-left: 10px;">
            <Button icon="ios-plus-empty" type="success" @click="addTicket">添加票</Button>
            </Col>

            <Modal title="添加票项" v-model="faceEdit" class-name="vertical-center-modal" @on-ok="ticketOk"
                   @on-cancel="ticketCencel" :mask-closable="false" :closable="false">
              <Form ref="ticketForm" :model="ticketData" inline>
                <FormItem label="票名">
                  <Input v-model="ticketData.name" placeholder="票名" required></Input>
                </FormItem>
                <FormItem label="票价">
                  <InputNumber :min="1" v-model="ticketData.price" placeholder="100" required></InputNumber>
                </FormItem>
                <FormItem label="票数">
                  <InputNumber :min="1" v-model="ticketData.count" placeholder="100" required></InputNumber>
                </FormItem>
              </Form>
            </Modal>
          </FormItem>
        </Form>
        <div class="margin-top-20">
          <mtext v-model="concert.content" @on-ready="onEditorReady"
                 @on-upload-complete="onEditorUploadComplete"></mtext>
        </div>
      </Card>
      </Col>

      <Col span="6" class="padding-left-10">
      <Card>
        <p slot="title">
          <Icon type="paper-airplane"></Icon>
          发布
        </p>
        <p class="margin-top-10">
          <Icon type="android-time"></Icon>&nbsp;&nbsp;状&nbsp;&nbsp;&nbsp; 态： {{checkStatus(concert.status)}}
        </p>
        <Row class="margin-top-10 publish-button-con">
                    <span class="publish-button">
                        <Button @click="handleSaveDraft">保存草稿</Button>
                    </span>
          <span class="publish-button">
                        <Button @click="handlePublish" :loading="publishLoading" icon="ios-checkmark"
                                style="width:90px;" type="primary">发布</Button>
                    </span>
        </Row>
      </Card>
      <div class="margin-top-10">
        <Card>
          <p slot="title">
            <Icon type="navicon-round"></Icon>
            分类目录
          </p>
          <Tabs type="card">
            <TabPane label="所有分类目录">
              <div class="classification-con">
                <RadioGroup v-model="concert.type" vertical>
                  <template v-for="item in classificationList">
                    <Radio :label="item.code">
                      {{item.name}}
                    </Radio>
                  </template>
                </RadioGroup>
              </div>
            </TabPane>
          </Tabs>
        </Card>
      </div>
      <div class="margin-top-10">
        <Card>
          <p slot="title">
            <Icon type="ios-pricetags-outline"></Icon>
            标签
          </p>
          <Row>
            <Col span="18">
            <Select v-model="concert.tags" multiple @on-change="handleSelectTag" placeholder="请选择文章标签">
              <Option v-for="item in articleTagList" :value="item.code" :key="item.code">{{ item.name }}</Option>
            </Select>
            </Col>
            <Col span="6" class="padding-left-10">
            <Button v-show="!addingNewTag" @click="handleAddNewTag" long type="ghost">新建</Button>
            </Col>
          </Row>
          <transition name="add-new-tag">
            <div v-show="addingNewTag" class="add-new-tag-con">
              <Col span="14">
              <Input v-model="newTagName" placeholder="请输入标签名"/>
              </Col>
              <Col span="5" class="padding-left-10">
              <Button @click="createNewTag" long type="primary">确定</Button>
              </Col>
              <Col span="5" class="padding-left-10">
              <Button @click="cancelCreateNewTag" long type="ghost">取消</Button>
              </Col>
            </div>
          </transition>
        </Card>
      </div>
      </Col>
    </Row>
  </div>
</template>

<script>
  import mtext from "components/mtext";

  export default {
    name: "Concert",
    components: {
      mtext
    },
    data() {
      return {
        bHeader: [
          {
            title: "日期",
            key: "date"
          },
          {
            title: "时间",
            key: "time"
          },
          {
            title: "操作",
            key: "action",
            width: 150,
            align: "center",
            render: (h, params) => {
              return h("div", [
                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.editTime(params.index);
                      }
                    }
                  },
                  "修改"
                ),
                h(
                  "Button",
                  {
                    props: {
                      type: "error",
                      size: "small"
                    },
                    on: {
                      click: () => {
                        this.removeTime(params.index);
                      }
                    }
                  },
                  "删除"
                )
              ]);
            }
          }
        ],
        cHeader: [
          {
            title: "票名",
            key: "name"
          },
          {
            title: "价格",
            key: "price"
          },
          {
            title: "数量",
            key: "count"
          },
          {
            title: "操作",
            key: "action",
            width: 150,
            align: "center",
            render: (h, params) => {
              return h("div", [
                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.editTicket(params.index);
                      }
                    }
                  },
                  "修改"
                ),
                h(
                  "Button",
                  {
                    props: {
                      type: "error",
                      size: "small"
                    },
                    on: {
                      click: () => {
                        this.removeTicket(params.index);
                      }
                    }
                  },
                  "删除"
                )
              ]);
            }
          }
        ],
        spinShow: false,
        publishLoading: false,
        posterShow: false,
        hasPoster: false,
        faceEdit: false,
        timeEdit: false,
        addingNewTag: false,
        defaultPoster: {
          id: '',
          imagePath: '',
          imageBase: ''
        },
        newTagName: "",
        uploadList: [],
        classificationList: [],
        classSelected: '',
        articleTagList: [],
        concert: {
          title: '',
          poster: '',
          tags: [],
          place: '',
          shortDesc: '',
          content: "<h1>Hello World</h1>",
          concertTime: [],
          seatType: "0",
          seatMapId: "",
          seats: '',
          type: "",
          minPrice: 100,
          beginOn: "",
          faceValues: [],
          status: '0'
        },
        ticketData: {},
        ticketNode: {
          index: 0,
          name: "",
          price: 1,
          count: 1
        },
        timeData: {},
        timeNode: {
          date: "",
          time: ["00:00"]
        }
      };
    },
    mounted() {
      this.init();
    },
    methods: {
      init() {
        let id = this.$route.params.id;
        if (id !== 'add') {
          this.$axios({
            method: 'get',
            url: `/api/concert/${id}`,
          }).then((res) => {
            let data = res.data;
            this.concert = data.result[0];
            this.concert.tags = this.concert.tags ? this.concert.tags.split(',') : [];
            this.loadConcertTime();
            this.loadFaceValues();
            this.loadImage(this.concert.poster);
          });
        }
        this.loadClassListData();
        this.loadTagListData();
      },
      loadConcertTime() {
        this.$axios({
          method: 'get',
          url: `/api/concertTime/${this.concert.id}`,
        }).then((res) => {
          let data = res.data;
          const concertTime = data.result? data.result:[];
          concertTime.forEach(e => {
            e.time = JSON.parse(e.time);
          });
          this.$set(this.concert, "concertTime", concertTime);
        }).catch(e => {
          console.log("can't load concert time"+e);
          this.$set(this.concert, "concertTime", []);
        });
      },
      loadFaceValues() {
        this.$axios({
          method: 'get',
          url: `/api/faceValues/${this.concert.id}`,
        }).then((res) => {
          let data = res.data;
          const faceValues = data.result? data.result:[];
          this.$set(this.concert, "faceValues", faceValues);
        }).catch(e => {
          console.log("can't load face values"+e);
          this.$set(this.concert, "faceValues", []);
        });
      },
      loadClassListData() {
        this.$axios({
          method: 'get',
          url: '/api/class',
          params: {
            cust: '0'
          }
        }).then(res => {
          this.classificationList = res.data.result;
          this.concert.type = this.concert.type ? ('list/' + this.concert.type) : this.classificationList[0].code;
        });
      },
      loadTagListData() {
        this.$axios({
          method: 'post',
          url: '/api/tags',
          data: {}
        }).then(res => {
          this.articleTagList = res.data.result;
        });
      },
      loadImage(imageId) {
        this.$axios({
          method: 'get',
          url: `/api/image/${imageId}`,
        }).then((res) => {
          this.defaultPoster = res.data;
          this.hasPoster = true;
          this.uploadList.push(this.defaultPoster);
        })
      },
      addTicket() {
        this.ticketData = Object.assign({}, this.ticketNode);
        this.faceEdit = true;
      },
      editTicket(index) {
        this.ticketData = Object.assign({}, this.concert.faceValues[index]);
        this.ticketData.isModified = true;
        this.ticketData.index = index;
        this.faceEdit = true;
      },
      removeTicket(index) {
        this.concert.faceValues.splice(index, 1);
      },
      ticketOk() {
        this.faceEdit = false;
        if (this.ticketData.isModified) {
          this.ticketData.isModified = false;
          this.concert.faceValues.splice(
            this.ticketData.index, 1,
            this.ticketData
          );
        } else {
          const obj = Object.assign({}, this.ticketData);
          this.concert.faceValues.push(obj);
        }
      },
      ticketCencel() {
        this.faceEdit = false;
      },
      addTime() {
        this.timeData = Object.assign({}, this.timeNode);
        this.timeEdit = true;
      },
      editTime(index) {
        this.timeData = Object.assign({}, this.concert.concertTime[index]);
        this.timeData.time = Object.assign([], this.concert.concertTime[index].time);
        this.timeData.isModified = true;
        this.timeData.index = index;
        this.timeEdit = true;
      },
      removeTime(index) {
        this.concert.concertTime.splice(index, 1);
      },
      addDateTime() {
        let newTimeData = Object.assign({}, this.timeData);
        newTimeData.time.push("");
        this.timeData = newTimeData;
      },
      timeOk() {
        this.clearEmptyTime();
        this.timeEdit = false;
        if (this.timeData.date === undefined || this.timeData.time.length <= 0) {
          return;
        }
        if (this.timeData.date instanceof Date) {
          this.timeData.date = this.timeData.date.toLocaleDateString();
        }
        if (this.timeData.isModified) {
          this.timeData.isModified = false;
          this.concert.concertTime.splice(this.timeData.index, 1, this.timeData);
        } else {
          const obj = Object.assign({}, this.timeData);
          this.concert.concertTime.push(obj);
        }
      },
      timeCencel() {
        this.clearEmptyTime();
        this.timeEdit = false;
      },
      clearEmptyTime() {
        if (this.concert.concertTime) {
          this.concert.concertTime.forEach(e => {
            e.time = e.time.filter(t => t != "");
          });
        }
        this.timeData.time = this.timeData.time.filter(e => e != "");
      },
      onEditorReady() {
      },
      onEditorUploadComplete([json, success, failure]) {
        success("http://localhost:8080/" + json.imagePath);
      },
      showPoster() {
        this.posterShow = true;
      },
      removePoster() {
        this.concert.poster = '';
        this.uploadList.splice(0, 1);
        this.$refs.upload.fileList = this.uploadList;
      },
      handleSuccess(res, file) {
        file.url = res.imageBase;
        file.name = res.imagePath;
        file.id = res.id;
        file.status = "finished";
        this.hasPoster = true;
        this.defaultPoster = res;
        this.concert.poster = res.id;
        this.uploadList.push(this.defaultPoster);
      },
      handleFormatError(file) {
        this.$Notice.warning({
          title: "The file format is incorrect",
          desc:
          "File format of " +
          file.name +
          " is incorrect, please select jpg or png."
        });
      },
      handleMaxSize(file) {
        this.$Notice.warning({
          title: "Exceeding file size limit",
          desc: "File  " + file.name + " is too large, no more than 2M."
        });
      },
      handleBeforeUpload() {
        const check = this.uploadList.length < 5;
        if (!check) {
          this.$Notice.warning({
            title: "Up to five pictures can be uploaded."
          });
        }
        return check;
      },
      checkStatus(status) {
        if (status == '1') return "已发布";
        else return "草稿";
      },
      handleProcess() {
        this.concert.tags = this.concert.tags.join();
        this.concert.type = this.concert.type.split('/')[1];
        if (this.concert.concertTime) {
          let beginOn = new Date(this.concert.concertTime[0].date).getTime();
          this.concert.concertTime.forEach(e => {
            let ctime = new Date(e.date).getTime();
            if (beginOn > ctime) {
              beginOn = ctime;
              this.concert.beginOn = e.date;
            }
          });
        }

        if (this.concert.faceValues) {
          let price = this.concert.faceValues[0].price;
          this.concert.faceValues.forEach(e => {
            if (price > e.price) {
              price = e.price;
              this.concert.minPrice = e.price;
            }
          });
        }

        this.concert.minPrice;
      },
      handleSaveDraft() {
        this.spinShow = true;
        this.handleProcess();
        let url = '/api/concert';
        if (this.concert.id) {
          url = url + `/${this.concert.id}`;
        }
        this.$axios({
          method: 'post',
          url: url,
          data: {
            concert: this.concert
          }
        }).then((res) => {
          this.spinShow = false;
          if (res.data.status === 'success') {
            this.$Notice.success({
              title: '保存成功!'
            });
            this.$router.push({
              path: `/admin/concert/${res.data.id}`,
            });
            this.init();
          } else {
            this.$Notice.error({
              title: '保存失败!'
            });
          }
        }).catch((error) => {
          this.spinShow = false;
          this.$Notice.error({
            title: '保存失败!'
          });
          console.log(error);
        });

      },
      handlePublish() {
        this.spinShow = true;
        this.publishLoading = true;
        this.$axios({
          method: 'put',
          url: `/api/concert/${this.concert.id}`,
          data: {
            status: '1'
          }
        }).then((res) => {
          this.spinShow = false;
          this.publishLoading = false;
          this.concert.status = '1';
          this.$Notice.success({
            title: '发布成功!'
          });
        }).catch((error) => {
          this.spinShow = false;
          this.publishLoading = false;
          this.$Notice.error({
            title: '发布失败!'
          });
        })

      },
      handleSelectTag() {
        sessionStorage.tagsList = JSON.stringify(this.concert.tags); // 本地存储文章标签列表
      },
      handleAddNewTag() {
        this.addingNewTag = true;
      },
      createNewTag() {
        if (this.newTagName.length !== 0) {
          let newTag = {};
          newTag.name = this.newTagName;
          newTag.code = Math.random().toString(36).substring(2);
          this.articleTagList.push({value: newTag.code, name: newTag.name});
          this.addingNewTag = false;
          this.$axios({
            method: 'post',
            url: '/api/tag',
            data: {
              tag: newTag,
            }
          }).then(res => {
            this.newTagName = '';
          });
        } else {
          this.$Message.error('请输入标签名');
        }
      },
      cancelCreateNewTag() {
        this.newTagName = '';
        this.addingNewTag = false;
      }
    }
  };
</script>

<style lang="css" scoped>
  .poster-upload {
    display: inline-block;
    width: 200px;
    height: 200px;
    text-align: center;
    line-height: 200px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
  }

  .poster-upload img {
    width: 100%;
    height: 100%;
  }

  .poster-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
  }

  .poster-upload:hover .poster-cover {
    display: block;
  }

  .poster-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }

  .add-new-tag-con {
    margin-top: 20px;
    border-top: 1px dashed #dbdddf;
    padding: 20px 0;
    height: 60px;
    overflow: hidden;
  }

  .classification-con {
    height: 180px;
    margin-top: -16px;
    border-left: 1px solid #dddee1;
    border-right: 1px solid #dddee1;
    border-bottom: 1px solid #dddee1;
    border-radius: 0 0 3px 3px;
    padding: 10px;
    overflow: auto;
  }
</style>
